package org.zfes.snowier.cloud.zbss.layer.tc.biz.service.impl;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.zfes.snowier.core.data.DataSet;
import org.zfes.snowier.core.data.Record;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.zfes.snowier.core.util.ZBeanUtil;
import org.zfes.snowier.core.util.ZStrUtil;
import org.zfes.snowier.core.util.ZAlert;
import org.zfes.snowier.core.util.ZAssert;
import org.zfes.snowier.core.idcenter.IDGenerator;
import org.zfes.snowier.common.dao.params.ParamMap;
import org.zfes.snowier.cloud.zbss.layer.tc.biz.service.IPercentageService;
import org.zfes.snowier.cloud.zbss.layer.tc.biz.service.IPractitionerService;
import org.zfes.snowier.cloud.zbss.layer.tc.biz.consts.BizConst;
import org.zfes.snowier.cloud.zbss.layer.tc.biz.dao.PercentageMapper;
import org.zfes.snowier.cloud.zbss.layer.tc.biz.model.Percentage;
import org.zfes.snowier.cloud.zbss.layer.tc.biz.model.Practitioner;

@Service
public class PercentageServiceImpl implements IPercentageService{
 	@Autowired
	private PercentageMapper percentageMapper;
 	@Autowired
	private IPractitionerService practitionerService;

 	private void setBaseVal(Percentage percentage) {
		Long practitionerId=percentage.getPractitionerId();
		ZAssert.notNull(practitionerId, "执业人员不能为空");
		Practitioner  practitioner=practitionerService.loadPractitionerById(practitionerId).orElseThrow(()->ZAlert.newSLE( "未查询到该执业人员"));
		percentage.setPractitionerName(practitioner.getName());
		
		if(percentage.getCooperPractitionerId()!=null) {
			Practitioner  cooperPractitioner=practitionerService.loadPractitionerById(percentage.getCooperPractitionerId()).orElseThrow(()->ZAlert.newSLE( "未查询到该合作律师信息"));
			percentage.setCooperPractitionerName(cooperPractitioner.getName());
		}
		Long zhiPaiPractitionerId=percentage.getZhiPaiPractitionerId();
		
		if(zhiPaiPractitionerId!=null) {
			Practitioner  zhiPaiPractitioner=practitionerService.loadPractitionerById(zhiPaiPractitionerId).orElseThrow(()->ZAlert.newSLE( "未查询到指派人员信息"));
			percentage.setZhiPaiPractitionerName(zhiPaiPractitioner.getName());
		}
		//percentage.setRecaordTime(ZDateUtil.toString(ZDateUtil.newDate(), ZDateStyle.YYYY_MM_DD));
 	}
	@Transactional(rollbackFor=Exception.class)
 	@Override
	public void createPercentage(Percentage percentage,String creator,String role) {
		ZBeanUtil.validateBean(percentage);
		percentage.setId(IDGenerator.genLongId());
		
		percentage.setCreator(creator);
		//2 审核，1 未审核
		if(BizConst.ROLE.R_USER.equals(role)) {
			percentage.setCheckStatus(Integer.valueOf("1"));
		}else {
			percentage.setCheckStatus(Integer.valueOf("2"));
		}
		
		
		Optional<Percentage> percentageOp= loadPercentageByCasNum( percentage.getCaseNum() );
		if(percentageOp.isPresent()) {
			ZAlert.newSLE("该案号已经存在");
		}
		
		if(ZStrUtil.hasText(percentage.getCaseFileNum())) {
			Optional<Percentage> percentageOp2 = loadPercentageByCaseFileNum( percentage.getCaseFileNum() );
			if(percentageOp2.isPresent()) {
				ZAlert.newSLE("该案卷号经存在");
			}
		}
		if(ZStrUtil.hasText( percentage.getCaseAgreementNum())) {
			Optional<Percentage> percentageOp3 = loadPercentageByCaseFileNum( percentage.getCaseAgreementNum() );
			if(percentageOp3.isPresent()) {
				ZAlert.newSLE("该合同号经存在");
			}
		}
		
		setBaseVal( percentage);
		
		
/*		Long orgId=practitioner.get().getOrgId();
		ZAssert.notNull(orgId, "该执业人员所属单位为空，请检查数据");
		percentage.setOrgId(orgId);*/
		
		percentageMapper.insertSelective(percentage);
	}
	
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void updatePercentage(Percentage percentage,String role) {
		ZBeanUtil.validateBean(percentage);
		
		//已提交，2已审核
		if(BizConst.ROLE.R_USER.equals(role)) {
			Percentage percentageIndb =loadPercentageById(percentage.getId()).orElseThrow(()->ZAlert.newSLE("数据不存在"));
			if(Integer.valueOf("2").equals(percentageIndb.getCheckStatus()) ){
				ZAlert.serviceLogicalError("该数据已经审核，您无权再修改");
			}
			
		}else {
			//percentage.setCheckStatus(Integer.valueOf("2"));
		}
		//防止数据重复
		Optional<Percentage> percentageOp = loadPercentageByCasNum( percentage.getCaseNum() );
		if(percentageOp.isPresent()&&!percentageOp.get().getId().equals(percentage.getId())) {
			ZAlert.newSLE("该案号已经存在");
		}
		if(ZStrUtil.hasText(percentage.getCaseFileNum())) {
			Optional<Percentage> percentageOp2 = loadPercentageByCaseFileNum( percentage.getCaseFileNum() );
			if(percentageOp2.isPresent()&&!percentageOp2.get().getId().equals(percentage.getId())) {
				ZAlert.newSLE("该案卷号经存在");
			}
		}
		if(ZStrUtil.hasText( percentage.getCaseAgreementNum() )) {
			Optional<Percentage> percentageOp3 = loadPercentageByCaseFileNum( percentage.getCaseAgreementNum() );
			if(percentageOp3.isPresent()&&!percentageOp3.get().getId().equals(percentage.getId())) {
				ZAlert.newSLE("该合同号经存在");
			}
		}
	
		setBaseVal( percentage);
		
		percentageMapper.updateByPrimaryKeySelective(percentage);
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	public  Optional<Percentage> loadPercentageByCasNum(String caseNum ) {
		if(ZStrUtil.hasText(caseNum)) {
			return Optional.empty();
		}
		return Optional.ofNullable(percentageMapper.selectByCasNum(caseNum));
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public Optional<Percentage> loadPercentageByCaseFileNum(String caseFileNum){
		if(ZStrUtil.hasText(caseFileNum)) {
			return Optional.empty();
		}
		return Optional.ofNullable(percentageMapper.selectByCaseFileNum(caseFileNum));
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public Optional<Percentage> loadPercentageByCaseAgreementNum(String caseAgreementNum){
		if(ZStrUtil.hasText(caseAgreementNum)) {
			return Optional.empty();
		}
		return Optional.ofNullable(percentageMapper.selectByCaseAgreementNum(caseAgreementNum));
	}
//	@Transactional(rollbackFor=Exception.class,readOnly=true)
//	@Override
//	public List<Percentage> loadByDefendantAndPlaintiffExchange(Long thisRecordId, String defendant, String plaintiff){
//		if(ZStrUtil.hasNoText(defendant)||ZStrUtil.hasNoText(plaintiff)){
//			return Collections.emptyList();
//		}
//		return percentageMapper.selectByDefendantAndPlaintiffExchange(thisRecordId, plaintiff, defendant);
//	}
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public List<Percentage> loadByWeiTuoRenName(Long id, String weiTuoRenName){
		if(ZStrUtil.hasText(weiTuoRenName)){
			return percentageMapper.selectByWeiTuoRenName( id,weiTuoRenName);
		}
		return Collections.emptyList();
	}
	 
//	@Transactional(rollbackFor=Exception.class,readOnly=true)
//	@Override
//	public List<Percentage> loadPercentageByPlaintiff(Long thisRecordId, String plaintiff) {
//		if(ZStrUtil.hasText(plaintiff)){
//			return percentageMapper.selectByPlaintiff( thisRecordId,plaintiff);
//		}
//		return Collections.emptyList();
//	}
	
	
//	@Transactional(rollbackFor=Exception.class,readOnly=true)
//	@Override
//	public List<Percentage> loadPercentageByDefendant(Long thisRecordId, String defendant) {
//		if(ZStrUtil.hasText(defendant)){
//			return percentageMapper.selectByDefendant( thisRecordId,defendant);
//		}
//		return Collections.emptyList();
//	}
	
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public Optional<Percentage> loadPercentageById(Long id) {
		if(id!=null){
			return Optional.ofNullable(percentageMapper.selectByPrimaryKey(id));
		}
		return Optional.empty();
	}

	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void deletPercentage(Long id) {
		if(id!=null){
			percentageMapper.deleteByPrimaryKey(id);
			return;
		}
		ZAlert.Error("请选择要删除的数据");
		
	}
	@Override
	public void updateCaseStatus(String type,List<Long> ids, int caseStatus) {
		ZAssert.notEmpty(ids, "请选择数据");
		if("liAn".equals(type)){
			ZAssert.isTrue((caseStatus==1||caseStatus==2), "状态错误");
			percentageMapper.updateCaseLiAnStatus(ids, caseStatus);
		}else if("jieAn".equals(type)){
			ZAssert.isTrue((caseStatus==1||caseStatus==2), "状态错误");
			percentageMapper.updateCaseJieAnStatus(ids, caseStatus);
		}else if("tuiFei".equals(type)){
		/*      <option value="0">未发生</option>
              <option value="1">未结清</option>
              <option value="2">已结清</option>
              <option value="3">终止委托</option>*/
			ZAssert.isTrue((0==caseStatus||caseStatus==1||caseStatus==2||caseStatus==3), "状态错误");
			percentageMapper.updateCaseTuiFeiStatus(ids, caseStatus);
		}else if("shenHe".equals(type)){
			ZAssert.isTrue((caseStatus==1||caseStatus==2), "状态错误");
			percentageMapper.updateCheckStatus(ids, caseStatus);
		}
		
	}

//	practitionerName: null,
//	practitionerId: null,
//		zhiPaiRenYuanId: null,
//		zhiPaiRenYuanNme: null,
//		caseNum: null,
//		weiTuoRenName: null,
//		startTime: null,
//		endTime: null,
//		caseLiAnStatus: null,
//		caseJieAnStatus: null,
//		caseTuiFeiStatus: null
	
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public DataSet loadPercentageDataSet(Map<String, Object> params) {
		//params.put("caseNum", null);
		ParamMap pm=ParamMap.filterParam(params);
		
		pm.getObj("caseNum").ifPresent(v->pm.updateParam("caseNum", "%"+v+"%"));
		
		pm.getObj("caseReason").ifPresent(v->pm.updateParam("caseReason", "%"+v+"%"));
		
		pm.getObj("weiTuoRenName").ifPresent(v->pm.updateParam("weiTuoRenName", "%"+v+"%"));
		
		DataSet ds=DataSet.newDS2(percentageMapper.selectListCount(pm), percentageMapper.selectMapListPage(pm));
		ds.getRows().add(percentageMapper.selectSumCount(pm).get(0));
		
		List<Record>  rx=percentageMapper.selectSumCount(pm);
		
		
		ds.setFooter((List<Map<String,Object>>)(List) rx);
		return ds;
	}
	

	
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public String loadNewCaseNum(String today){
		today=today.replaceAll("-", "");
		String asd=percentageMapper.selectMaxCaseNumInDate(today+"%");
		if(ZStrUtil.hasText(asd)){
			asd=asd.replace(today, "");
			int next=Integer.parseInt(asd)+1;
			String res=next<10?("0"+next):""+next;
			return today+res;
		}
		return today+"01";
	}
//	@Transactional(rollbackFor=Exception.class,readOnly=true)
//	@Override
//	public DataSet loadPercentageDataSetForExport(Map<String, Object> params) {
//		
//		params.remove("practitionerId");
//		params.remove("cooperPractitionerId");
//		params.remove("zhiPaiRenYuanId");
//		params.remove("orgId");
//		params.remove("caseNum");
//		params.remove("clientName");
//		params.remove("caseStatusLiAn");
//		params.remove("caseStatusJieAn");
//		ParamMap pm=ParamMap.filterParam(params);
//		Optional<Object> obj=pm.getObj("qp_practitionerId");
//		if(obj.isPresent()){
//			System.out.println(obj.get());
//			pm.updateParam("practitionerId",obj.get());
//		}
//		pm.getObj("qp_practitionerId").ifPresent(v->pm.updateParam("practitionerId",v));
//		pm.getObj("qp_cooperPractitionerId").ifPresent(v->pm.updateParam("cooperPractitionerId",v));
//		pm.getObj("qp_zhiPaiRenYuanId").ifPresent(v->pm.updateParam("zhiPaiRenYuanId", v));
//		//pm.getObj("qp_orgId").ifPresent(v->pm.updateParam("orgId", v));
//		
//		pm.getObj("qp_startTime").ifPresent(v->pm.updateParam("startTime", v));
//		pm.getObj("qp_endTime").ifPresent(v->pm.updateParam("endTime", v));
//		pm.getObj("qp_caseNum").ifPresent(v->pm.updateParam("caseNum", "%"+v+"%"));
//		pm.getObj("qp_clientName").ifPresent(v->pm.updateParam("clientName", "%"+v+"%"));
//		pm.getObj("qp_caseStatusLiAn").ifPresent(v->pm.updateParam("caseStatusLiAn", v));
//		pm.getObj("qp_caseStatusJieAn").ifPresent(v->pm.updateParam("caseStatusJieAn", v));
//		
//		Long count=percentageMapper.selectListCount(pm);
//		pm.setSize(count);
//		pm.setRows(count);
//		DataSet ds=DataSet.newDS(count, percentageMapper.selectList(pm));
//		//ds.getRows().add(percentageMapper.selectSumCount(pm).get(0));
//		ds.setFooter(percentageMapper.selectSumCount(pm));
//		return ds;
//	}
	
	

	
}